#
# Copyright 2008 Andi Albrecht <albrecht.andi@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import threading

from django.conf import settings

from gae2django.utils import CallableString, patch_user

_thread_locals = threading.local()


# get_current_user hack found here:
#   http://lukeplant.me.uk/blog.php?id=1107301634


def get_current_user():
    user = getattr(_thread_locals, 'user', None)
    if user and user.is_anonymous():
        return None
    return user


class FixRequestUserMiddleware(object):

    def process_request(self, request):
        _thread_locals.user = getattr(request, 'user', None)
        if getattr(request, 'user', None) is None:
            return
        if not request.user.is_anonymous():
            patch_user(request.user)
            try:
                profile = request.user.get_profile()
                if hasattr(profile, 'nickname'):
                    request.user.nickname = CallableString(profile.nickname)
            except:
                pass
        else:
            request.user.email = CallableString()
            request.user.nickname = CallableString()
